package cn.cloud9.designpattern.dp01singleton;

import java.io.*;

/**
 * @author OnCloud9
 * @description
 * @project Java
 * @date 2022年05月22日 16:26
 */
public class Singleton10 implements Serializable {

    private Singleton10() {}

    private static final Singleton10 INSTANCE = new Singleton10();

    public static Singleton10 getInstance() {
        return INSTANCE;
    }

    public static void main(String[] args) throws Exception {
        final String FILE_NAME = "Singleton.obj";

        // 输出流资源
        OutputStream fileOutputStream = null;
        ObjectOutputStream outputStream = null;
        // 输入流资源
        InputStream fileInputStream = null;
        ObjectInputStream objectInputStream = null;
        try {
            Singleton10 s1 = Singleton10.getInstance();
            Singleton10 s2 = null;

            // 序列化 -> 输出到文件
            fileOutputStream = new FileOutputStream(FILE_NAME);
            outputStream = new ObjectOutputStream(fileOutputStream);
            outputStream.writeObject(s1);

            // 反序列化 -> 从文件中读取
            fileInputStream = new FileInputStream(FILE_NAME);
            objectInputStream = new ObjectInputStream(fileInputStream);
            final Object readObject = objectInputStream.readObject();
            s2 = (Singleton10) readObject;

            System.out.println(s1);
            System.out.println(s2);
            System.out.println(s1 == s2);

        } catch (Exception exception) {
            exception.printStackTrace();
        } finally {
            // 关闭资源
            outputStream.flush();
            outputStream.close();

            fileOutputStream.flush();
            fileOutputStream.close();

            objectInputStream.close();
            fileInputStream.close();
        }



    }
}
